Page({
  data: {
    nickname: '蒋大大大大大',
    avatarUrl: '/assets/images/avatar.jpg',
    defaultAvatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=256&h=256&fit=crop&auto=format',
    score: '-',
    times: '-',
    bestScore: '-',
    version: '',
    showAvatarActions: false
  },
  onLoad() {
    const date = new Date();
    const y = date.getFullYear();
    const m = `${date.getMonth() + 1}`.padStart(2, '0');
    const d = `${date.getDate()}`.padStart(2, '0');
    const version = `${y}${m}${d}`;
    const saved = wx.getStorageSync('profile') || {};
    this.setData({
      version,
      nickname: saved.nickname || this.data.nickname,
      avatarUrl: saved.avatarUrl || this.data.avatarUrl,
      score: saved.score || this.data.score,
      times: saved.times || this.data.times,
      bestScore: saved.bestScore || this.data.bestScore
    });
  },
  onShow() {
    const tabBar = this.getTabBar && this.getTabBar();
    if (tabBar && typeof tabBar.setSelected === 'function') {
      tabBar.setSelected(2);
    }
  },
  onNickInput(e) {
    const nickname = e.detail.value;
    this.setData({ nickname });
    this.persistProfile({ nickname });
  },
  onScoreInput(e) {
    const score = e.detail.value;
    this.setData({ score });
    this.persistProfile({ score });
  },
  onTimesInput(e) {
    const times = e.detail.value;
    this.setData({ times });
    this.persistProfile({ times });
  },
  onBestScoreInput(e) {
    const bestScore = e.detail.value;
    this.setData({ bestScore });
    this.persistProfile({ bestScore });
  },
  onToggleAvatarActions() {
    this.setData({ showAvatarActions: !this.data.showAvatarActions });
  },
  onChooseAvatar(e) {
    const avatarUrl = e.detail && e.detail.avatarUrl;
    if (avatarUrl) {
      this.setData({ avatarUrl, showAvatarActions: false });
      this.persistProfile({ avatarUrl });
    }
  },
  onPickImage() {
    wx.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['album','camera'], success: (res) => {
      const path = res.tempFilePaths && res.tempFilePaths[0];
      if (path) {
        this.setData({ avatarUrl: path, showAvatarActions: false });
        this.persistProfile({ avatarUrl: path });
      }
    }});
  },
  onAvatarError() {
    // fallback to default avatar if local path missing or load failed
    this.setData({ avatarUrl: '', showAvatarActions: false });
  },
  persistProfile(partial) {
    const current = wx.getStorageSync('profile') || {};
    wx.setStorageSync('profile', { ...current, ...partial });
  }
});


